//
//  PPUserInfoTableViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 8/19/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPSelfInfoTableViewController.h"
#import "QRCodeGenerator.h"
#import "SBJson.h"
#import "PPUserQRCodeViewController.h"
#import "PPCameraAuthorization.h"

@interface PPSelfInfoTableViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate>



@property (nonatomic, weak) PPSystemConfiguraton *config;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property(nonatomic, strong) PPUserInfo *user;

@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
//edit use
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *userAgeTextField;
@property (weak, nonatomic) IBOutlet UITextField *cityTextField;
@property (weak, nonatomic) IBOutlet UISegmentedControl *genderSegment;
@property (weak, nonatomic) IBOutlet UITextView *signatureTextView;
//display use
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *genderLabel;
@property (weak, nonatomic) IBOutlet UILabel *signatrueLabel;


@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;

@property (nonatomic) BOOL isEdit;//判断是编辑还是展示状态

//UIPicker
@property (nonatomic, strong) UIPickerView *addressPickerView;
@property (strong, nonatomic) UIToolbar *toolBar;
@property (strong, nonatomic) UIBarButtonItem *cancelButton;
@property (strong, nonatomic) UIBarButtonItem *doneButton;

@property (nonatomic, strong) NSArray *provinceArray;
@property (nonatomic, strong) NSArray *cityArray;

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (nonatomic, strong) UIToolbar *dateToolBar;
@property (nonatomic, strong) UIBarButtonItem *dateDoneButton;
@property (nonatomic, strong) UIBarButtonItem *dateCancelButton;
@property (nonatomic, strong) NSDateFormatter *formatter;
@end

@implementation PPSelfInfoTableViewController
//date picker view
- (NSDateFormatter *)formatter
{
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [_formatter setTimeZone:timeZone];
        [_formatter setDateFormat:@"yyyy/MM/dd"];
    }
    return _formatter;
}
//UIDatePicker
- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
    }
    return _datePicker;
}
- (UIToolbar *)dateToolBar
{
    if (!_dateToolBar) {
        _dateToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.dateCancelButton, space, self.dateDoneButton, nil];
        [_dateToolBar setItems:toolBarItems];
    }
    return _dateToolBar;
}
- (UIBarButtonItem *)dateCancelButton
{
    if (!_dateCancelButton) {
        _dateCancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
    }
    return _dateCancelButton;
}
- (UIBarButtonItem *)dateDoneButton
{
    if (!_dateDoneButton) {
        _dateDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
    }
    return _dateDoneButton;
}

- (void)cancelDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.userAgeTextField isFirstResponder]) {
        [self.userAgeTextField resignFirstResponder];
    }
}
- (void)doneDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.userAgeTextField isFirstResponder]) {
        [self.userAgeTextField resignFirstResponder];
        self.userAgeTextField.text = [self.formatter stringFromDate:self.datePicker.date];
//        self.my.Userbirthday=self.userBirthTextField.text;
//        NSLog(@"___%@",self.my.Userbirthday);
    }
}



//picker view
-(UIPickerView *)addressPickerView
{
    if (!_addressPickerView) {
        _addressPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
        _addressPickerView.delegate = self;
        _addressPickerView.dataSource = self;
    }
    return _addressPickerView;
}

-(UIToolbar *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.cancelButton, space, self.doneButton, nil];
        [_toolBar setItems:toolBarItems];
    }
    return _toolBar;
}

- (UIBarButtonItem *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];
    }
    return _cancelButton;
}

- (UIBarButtonItem *)doneButton
{
    if (!_doneButton) {
        _doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];
    }
    return _doneButton;
}

- (void)cancelButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.cityTextField isFirstResponder]) {
        [self.cityTextField resignFirstResponder];
    }
    
}

- (void)doneButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.cityTextField isFirstResponder]) {
        [self.cityTextField resignFirstResponder];
        
//        self.petType = [self.cityTextField objectAtIndex:[self.petPickerView selectedRowInComponent:0]];
//        self.petBreed = [self.petBreedArray objectAtIndex:[self.petPickerView selectedRowInComponent:1]];
        self.cityTextField.text = [self.cityArray objectAtIndex:[self.addressPickerView selectedRowInComponent:1]];
    }
}


-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}
- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

//-(void) viewWillDisappear:(BOOL)animated {
//    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
//        //捕获backButton事件
//    }
//    
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //get city
    self.provinceArray = [AreaGetter provinces];
    self.cityArray = [AreaGetter citiesForProvince:[self.addressPickerView selectedRowInComponent:0]];
    self.isEdit = NO;
    self.user = self.config.userInfo;
    [self delegateSet];
    [self userInfoLoad];
    [self viewStyleSet];
    //QRCode
//    NSDictionary *userIdDic = @{@"userid": @(self.user.id)};
//    NSString *userIdString = [userIdDic JSONRepresentation];
//    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
//                                   initWithTitle: @"Servers"
//                                   style:UIBarButtonItemStylePlain
//                                   target:self
//                                   action:@selector(back)];
//    [backButton setImage:[UIImage imageNamed:@"Wback"]];
//    self.navigationItem.leftBarButtonItem = backButton;
    
    
//    UIButton  *backButton = [[UIButton alloc]init];
//    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//    [backButton setImage:[UIImage imageNamed:@"Wback"] forState:UIControlStateNormal];
//    [backButton setImage:[UIImage imageNamed:@"Wback"] forState:UIControlStateHighlighted];
//    [backButton setTitle:@"返回" forState:UIControlStateNormal];
//    [backButton sizeToFit];
//    UIBarButtonItem *barbutton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
//    [self.navigationItem.leftBarButtonItem setAction:@selector(back)];
//    [self.navigationItem.leftBarButtonItem setTarget:self];
    
}



//- (void)back{
//    [self.config getUserInfowithComepletion:^{
//        NSLog(@"返回了");
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
//
//}


-(void)delegateSet
{
    self.userNameTextField.delegate = self;
    self.userAgeTextField.delegate = self;
    self.cityTextField.delegate = self;
    self.signatureTextView.delegate =self;
    
    self.cityTextField.inputView = self.addressPickerView;
    self.cityTextField.inputAccessoryView = self.toolBar;
    
    self.userAgeTextField.inputView = self.datePicker;
    self.userAgeTextField.inputAccessoryView = self.dateToolBar;
}

-(void)userInfoLoad
{
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageSet)];
    self.avatarImageView.userInteractionEnabled = YES;
    recognizer.numberOfTouchesRequired = 1;
    recognizer.numberOfTapsRequired = 1;
    [self.avatarImageView addGestureRecognizer:recognizer];
    
    [self.avatarImageView setImageWithURL:[PPImageUrl getImageUrl:self.user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    self.userNameLabel.text = self.user.userName;
    self.ageLabel.text = self.user.birth;
    self.addressLabel.text = self.user.address;
    self.signatrueLabel.text = self.user.signature;
    
    switch (self.user.gender) {
        case 0:
            self.genderLabel.text = @"先生";
            break;
        case 1:
            self.genderLabel.text = @"女士";
            break;
        default:
            self.genderLabel.text = @"保密";
            break;
    }
}

-(void)viewStyleSet
{
    if (self.isEdit) {
        self.userNameTextField.hidden = NO;
        self.userAgeTextField.hidden = NO;
        self.cityTextField.hidden = NO;
        self.signatureTextView.hidden = NO;
        self.genderSegment.hidden = NO;
        
        self.userNameLabel.hidden = YES;
        self.ageLabel.hidden = YES;
        self.addressLabel.hidden = YES;
        self.genderLabel.hidden = YES;
        self.signatrueLabel.hidden = YES;
    }else{
        self.userNameTextField.hidden = YES;
        self.userAgeTextField.hidden = YES;
        self.cityTextField.hidden = YES;
        self.signatureTextView.hidden = YES;
        self.genderSegment.hidden = YES;
        
        self.userNameLabel.hidden = NO;
        self.ageLabel.hidden = NO;
        self.addressLabel.hidden = NO;
        self.genderLabel.hidden = NO;
        self.signatrueLabel.hidden = NO;
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Pick view data soure

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView//返回选择器组件数
{
    return 2;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component//选择器的选项个数
{
    if (component == 0) {
        return self.provinceArray.count;
    }else{
        return self.cityArray.count;
    }
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 0) {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.provinceArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }else{
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.cityArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.cityArray = [AreaGetter citiesForProvince:[self.addressPickerView selectedRowInComponent:0]];
        [self.addressPickerView reloadComponent:1];
    }
}


#pragma mark - Table View delegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 14.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 14)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - ActionSheet

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }else if (buttonIndex == 1) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (IS_OS_7_OR_LATER) {
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }
        }else{
            [self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickContrillerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    [self.avatarImageView setImage:image];
    NSString *filePathString = [self uploadUserAvatar:self.avatarImageView.image];
    image = nil;
    //上传头像
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        [HUD showUIBlockingIndicatorWithText:@"头像正在上传"];
        NSString *url = [PPAPIList getAPIList].PPUpdateUserMsgByUserId;
        NSDictionary *params = @{@"userId":@(self.config.userInfo.id)};
        [httpRequst POST:url parameters:params imagePath:filePathString imageName:@"userAvatar" keyWords:@"userAvatar" success:^(AFHTTPRequestOperation *operation , id responseObject){
            [self alertSet:@"头像上传成功"];
            [HUD hideUIBlockingIndicator];
        }failure:^(AFHTTPRequestOperation *operation,NSError *error){
            [self alertSet:@"头像上传失败"];
            [HUD hideUIBlockingIndicator];
        }];
    }];
}



- (NSString *)uploadUserAvatar:(UIImage *)image
{
    NSData *data;
    if (UIImagePNGRepresentation(image).length > 2100000) {
        data = UIImageJPEGRepresentation(image, 0.5);
    }else{
        data = UIImagePNGRepresentation(image);
    }
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/userAvatar.png"] contents:data attributes:nil];
    //得到选择后沙盒中图片的完整路径 并返回
    return [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/userAvatar.png"];
}





#pragma mark - Custom IBAction

- (IBAction)saveUserInfo:(id)sender {
    if (self.isEdit) {
        [self.userNameTextField resignFirstResponder];
        [self.userAgeTextField resignFirstResponder];
        [self.cityTextField resignFirstResponder];
        [self.signatureTextView resignFirstResponder];
        //check
        if (!self.userNameTextField.text.length > 0) {
            [self alertSet:@"请填写用户昵称"];
            return;
        }
        
        if (!self.userAgeTextField.text.length > 0) {
            [self alertSet:@"请填写生日"];
            return;
        }
        
        if (!self.cityTextField.text.length > 0) {
            [self alertSet:@"请填写地址"];
            return;
        }
        //save
        NSString *url = [PPAPIList getAPIList].PPUpdateUserMsgByUserId;
        NSDictionary *params = @{@"userId":@(self.user.id),
                                 @"userName":self.userNameTextField.text,
                                 @"birth":self.userAgeTextField.text,
                                 @"address":self.cityTextField.text,
                                 @"gender":@(self.genderSegment.selectedSegmentIndex),
                                 @"signature":self.signatureTextView.text
                                 };
        [HUD showUIBlockingIndicatorWithText:@"正在保存"];
        [httpRequst POST:url parameters:params imagePath:nil imageName:nil keyWords:nil success:^(AFHTTPRequestOperation *operation , id responseObject){
            [HUD hideUIBlockingIndicator];
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                //save success
                [self.saveButton setTitle:@"编辑"];
                self.isEdit = NO;
                [self changeValueBetweenLabelWithTextFiled];
                [self viewStyleSet];
            }
        }failure:^(AFHTTPRequestOperation *operation,NSError *error){
            [self alertSet:@"保存失败,请重试！"];
            [HUD hideUIBlockingIndicator];
        }];
    }else{
        [self.saveButton setTitle:@"保存"];
        self.isEdit = YES;
        [self changeValueBetweenLabelWithTextFiled];
        [self viewStyleSet];
    }
}

#pragma mark - Custom Method

-(void)alertSet:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

-(void)changeValueBetweenLabelWithTextFiled
{
    if (self.isEdit) {
        //label to textfiled
        self.userNameTextField.text = self.userNameLabel.text;
        self.userAgeTextField.text = self.ageLabel.text;
        self.cityTextField.text = self.addressLabel.text;
        self.signatureTextView.text = self.signatrueLabel.text;
        if ([self.genderLabel.text isEqualToString:@"先生"]) {
            self.genderSegment.selectedSegmentIndex = 0;
        }else{
            self.genderSegment.selectedSegmentIndex = 1;
        }
    }else{
        self.userNameLabel.text = self.userNameTextField.text;
        self.ageLabel.text = self.userAgeTextField.text;
        self.addressLabel.text = self.cityTextField.text;
        self.signatrueLabel.text = self.signatureTextView.text;
        
        switch (self.genderSegment.selectedSegmentIndex) {
            case 0:
                self.genderLabel.text = @"先生";
                break;
            case 1:
                self.genderLabel.text = @"女士";
                break;
            default:
                break;
        }
    }
}

-(void)imageSet
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.tableView];
    
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"UserInfoToMyQR"]) {
        PPUserQRCodeViewController *targetVC = segue.destinationViewController;
        targetVC.user = self.user;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

#pragma mark - UITextFiled delegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.userAgeTextField]) {
        [self.datePicker setDatePickerMode:UIDatePickerModeDate];
        [self.datePicker setMaximumDate:[NSDate date]];
        [self.datePicker setMinimumDate:nil];
        [self.formatter setDateFormat:@"yyyy/MM/dd"];
        NSDate *currentDate;
        if (textField.text.length > 0) {
            currentDate = [self.formatter dateFromString:self.userAgeTextField.text];
        }else{
            currentDate = [NSDate date];
        }
        [self.datePicker setDate:currentDate];
        
    }
    return YES;
}

@end
